<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Medal Class
 *
 * @category	Home
 */
class MedalAction extends HomeAction
{

	protected $Medal;

	
	public function _initialize()
	{
		parent::_initialize();
		$this->Medal = D('Medal');
	}


	//勋章列表
	public function index()
	{
	    $map = array('status' => 1);
	    $order = array('display_order' => 'asc');
        $medals = $this->Medal->where($map)->order($order)->select();

        $this->assign('medals', $medals);
        $this->display();
	}


	//申请勋章
	public function apply()
	{

	    $medalID = intval($_GET['mid']);
	    $medal = $this->Medal->find($medalID);

	    if (empty($this->_user['user_id']))
	    {
	        $this->redirect('Account/login');
	    }

	    if (empty($medal))
	    {
	    	$this->error(L('medal_not_existed'));
	    }

	    if (2 != $medal['award_type'])
	    {
	    	$this->error(L('no_perms_action'));
	    }

	    $myMedals = explode(',', $this->_user['medal']);
	    if (!empty($myMedals) && in_array($medalID, $myMedals))
	    {
	    	$this->error(L('medal_existed'));
	    }

	    $where = 'user_id='. $this->_user['user_id'] .' AND '. $medal['permission'];
	    $count = $this->_User->where($where)->count();
	    if (intval($count) < 1)
	    {
	    	$this->error(L('no_apply_medal_perms'));
	    }

        $MedalLog = M('MedalLog');
        $data = array(
            'user_id'     => intval($this->_user['user_id']),
            'medal_id'    => intval($medalID),
            'create_time' => time(),
            'expire_time' => $medal['expiration'] ? time() + $medal['expiration'] * 86400 : 0,
            'type'        => 2,
            'status'      => 1,
        );
        $MedalLog->add($data);

        $myMedals[] = $medalID;
        $myMedals = implode(',', array_unique($myMedals));
        $where = array('user_id' => $this->_user['user_id']);
        $this->_User->where($where)->setField('medal', $myMedals);

        $this->success(L('medal_applied'));
	}

}
// End  Class

/* End of file MedalAction.class.php */
/* Location: ./App/Lib/Action/Home/MedalAction.class.php */